<template>
  <div class="paper-container">
    <!-- 加载动画层 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
    </div>

    <h2 class="title">论文生成</h2>

    <!-- 步骤导航 -->
    <div class="steps">
      <button v-for="n in 4" :key="n" :class="{ 'active': step === n, 'completed': step > n }" @click="goToStep(n)"
        :disabled="step < n">
        步骤 {{ n }}
      </button>
    </div>

    <!-- 步骤 1：论文基本信息 -->
    <div v-if="step === 1" class="step-content">
      <div class="input-group">
        <label for="title">论文标题</label>
        <input id="title" v-model="title" :class="{ 'filled': title, 'empty': !title }" placeholder="输入标题，或者尝试推荐标题"
          @blur="validateTitle" />
        <p v-if="titleError" class="error-message">标题不能为空！</p>
      </div>

      <div class="input-group">
        <label for="topicDescription">论文主题描述</label>
        <textarea id="topicDescription" v-model="topicDescription"
          :class="{ 'filled': topicDescription, 'empty': !topicDescription }" placeholder="简要描述你的论文主题，添加关键词..."
          @blur="validateDescription"></textarea>
        <p v-if="descriptionError" class="error-message">论文主题描述不能为空！</p>
      </div>

      <!-- 学历选择 -->
      <div class="radio-group">
        <label class="fristLabel">选择学历：</label>
        <label><input type="radio" value="大专" v-model="educationLevel" /> 大专</label>
        <label><input type="radio" value="本科" v-model="educationLevel" /> 本科</label>
        <label><input type="radio" value="硕士" v-model="educationLevel" /> 硕士</label>
      </div>

      <!-- 论文字数选择 -->
      <div class="radio-group">
        <label class="fristLabel">选择字数：</label>
        <label><input type="radio" value="3000" v-model="wordCount" /> 3000字</label>
        <label><input type="radio" value="5000" v-model="wordCount" /> 5000字</label>
        <label><input type="radio" value="10000" v-model="wordCount" /> 10000字</label>
        <label>
          <input type="radio" :value="customWordCount" v-model="wordCount" />
          自定义字数
          <input type="number" v-model="customWordCount" @input="updateCustomWordCount" placeholder="输入字数" />
        </label>
      </div>


      <!-- 须知复选框 -->
      <div class="checkbox-group">
        <label>
          <input type="checkbox" v-model="agree" />
          我已阅读并同意：生成的论文仅供参考，不作为毕业、发表使用
        </label>
      </div>
      <button @click="$router.go(-1)">返回</button>
      <button @click="nextStep" :disabled="!agree || !title || !topicDescription">下一步</button>
    </div>

    <!-- 步骤 2：论文大纲 -->
    <div v-if="step === 2" class="step-content">

      <div class="outline-container">
        <h3>论文大纲</h3>
        <div v-for="(section, index) in outlineSectionsData" :key="index" class="outline-item">
          <textarea v-model="outlineSectionsData[index]" class="outline-textarea"></textarea>
        </div>
      </div>


      <button @click="prevStep">上一步</button>
      <button @click="nextStep">下一步</button>
    </div>

    <!-- 步骤 3：论文正文格式-->
    <div v-if="step === 3" class="step-content">

      <h3>格式设置</h3>
      <div class="format-settings-container">
        <div class="format-setting">
          <label for="fontSize">字体大小：</label>
          <div class="custom-select">
            <select v-model="fontSize" id="fontSize">
              <option value="12">12px</option>
              <option value="14">14px</option>
              <option value="16">16px</option>
              <option value="18">18px</option>
            </select>
            <span class="select-arrow">▼</span>
          </div>
        </div>

        <div class="format-setting">
          <label for="indentation">正文缩进：</label>
          <div class="custom-select">
            <select v-model="indentation" id="indentation">
              <option value="0">无缩进</option>
              <option value="20">2em 缩进</option>
              <option value="40">4em 缩进</option>
            </select>
            <span class="select-arrow">▼</span>
          </div>
        </div>

        <div class="format-setting">
          <label for="headingSize">标题大小：</label>
          <div class="custom-select">
            <select v-model="headingSize" id="headingSize">
              <option value="24">24px</option>
              <option value="28">28px</option>
              <option value="32">32px</option>
            </select>
            <span class="select-arrow">▼</span>
          </div>
        </div>

        <div class="format-setting">
          <label for="lineHeight">行间距：</label>
          <div class="custom-select">
            <select v-model="lineHeight" id="lineHeight">
              <option value="1">1.0</option>
              <option value="1.5">1.5</option>
              <option value="2">2.0</option>
            </select>
            <span class="select-arrow">▼</span>
          </div>
        </div>
      </div>

      <div class="button-group">
        <button @click="prevStep">上一步</button>
        <button @click="generatePaper" class="generate-btn">生成论文</button>
      </div>
    </div>
  </div>

</template>

<script>
import { getOutline1, getOutline2 } from "@/api/structure";
import { generatePaper } from "@/api/essay";
import useUserStore from '@/store/modules/user'; // 根据你的实际路径调整
const userStore = useUserStore();
const wordCount = ref('3000'); // 默认字数
const customWordCount = ref(''); // 自定义字数
const lineHeight = ref('1'); // 行间距，默认值为 1.0

const updateCustomWordCount = () => {
  if (wordCount.value !== customWordCount.value) {
    wordCount.value = customWordCount.value; // 更新选中的字数为自定义字数
  }
};

export default {
  data() {
    return {
      id: userStore.id,
      step: 1,
      title: "",
      topicDescription: "",
      generatedPaper: null,
      titleError: false,
      descriptionError: false,
      outlines: [], // 用于存储从后端获取的原始数据
      outlineSectionsData: [], // 用于存储大纲数据的可写数组
      agree: false, // 添加 agree 属性，并初始化为 false
      educationLevel: "", // 添加教育水平的初始值
      wordCount: "",// 添加字数选择的初始值
      fontSize: "12", // 字体大小
      indentation: "0", // 正文缩进
      headingSize: "24", // 标题大小
      lineHeight: "1", // 行间距
      isLoading: false, // 新增加载状态
    };
  },
  computed: {
    // 计算属性，用于提取和过滤大纲数据
    outlineSections() {
      if (this.outlines.length > 0) {
        // 提取第一个对象的所有值，并过滤掉 null 或 undefined 值
        return Object.values(this.outlines[0]).filter(Boolean);
      }
      return [];
    }
  },
  watch: {
    // 监听 outlineSections 的变化，并更新 outlineSectionsData
    outlineSections: {
      immediate: true,
      handler(newSections) {
        this.outlineSectionsData = [...newSections];
      }
    }
  },
  methods: {
    nextStep() {
      if (this.step < 4) this.step++;
    },
    prevStep() {
      if (this.step > 1) this.step--;
    },
    goToStep(n) {
      if (n <= this.step) this.step = n;
    },
    async generatePaper() {
      this.isLoading = true; // 开始加载
      try {
        const paperData = {
          title: this.title,
          topicDescription: this.topicDescription,
          educationLevel: this.educationLevel,
          wordCount: this.wordCount,
          outlineSections: this.outlineSectionsData, // 大纲数据
          fontSize: this.fontSize,
          indentation: this.indentation,
          headingSize: this.headingSize,
          lineHeight: this.lineHeight
        };
        console.log(paperData)
        const response = await generatePaper(paperData);
        console.log(response)
        if (response) {
          console.log('接收到的数据:', response.data.content);
          this.$router.push({
            name: 'Quill',
            query: {
              generatedPaper: response.data.content,
              fontSize: this.fontSize,
              indentation: this.indentation,
              headingSize: this.headingSize,
              lineHeight: this.lineHeight
            }
          });
        }
      } catch (error) {
        console.error('生成失败:', error);
        alert('论文生成失败，请重试');
      } finally {
        this.isLoading = false; // 无论成功失败都隐藏加载
      }
    },
    async fetchOutlines() {
      try {
        const response1 = await getOutline1();
        const response2 = await getOutline2();
        console.log(response1);
        console.log(response2);
        // 合并两个响应的数据
        this.outlines = [...response1, ...response2];
      } catch (error) {
        console.error("获取大纲失败:", error);
      }
    }
  },
  mounted() {
    this.fetchOutlines();
  }
};
</script>
<style scoped>
.paper-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #f8f9fc;
  border-radius: 8px;
}

.title {
  text-align: center;
  font-size: 24px;
  color: #6a5acd;
}

.steps {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.steps button {
  margin: 0 5px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background: #ccc;
  color: #fff;
}

.steps button.active {
  background-color: #6a5acd;
}

.steps button.completed {
  background-color: #8a2be2;
}

.steps button:disabled {
  background: #d3d3d3;
  cursor: not-allowed;
}

.step-content {
  padding: 20px;
  background: #ffffff;
  border-radius: 6px;
  box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
  padding-bottom: 60px;
  /* 给按钮留出空间 */
}

.input-group,
.radio-group,
.checkbox-group {
  margin-bottom: 15px;
}

.input-group input,
.input-group textarea {
  width: 100%;
  padding: 8px;
  margin-right: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

textarea {
  height: 100px;
}

button {
  padding: 8px 16px;
  background: #6a5acd;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.alert-message {
  color: red;
  margin-top: 10px;
}

.outline-container {
  margin-top: 20px;
}

.outline-item {
  margin-bottom: 10px;
}

.outline-textarea {
  width: 100%;
  height: 60px;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ccc;
}

.input-group label,
.radio-group label,
.checkbox-group label {
  position: relative;
  padding-left: 12px;
  margin-bottom: 8px;
  display: block;
}

/* 左侧竖线效果 */
.input-group label::before,
.radio-group .fristLabel::before {
  content: '';
  position: absolute;
  left: 0;
  top: 2px;
  bottom: 2px;
  width: 3px;
  background: #6a5acd;
  border-radius: 2px;
}

/* 单选按钮样式 */
.radio-group label {
  display: flex;
  align-items: center;
  margin: 8px 0;
  cursor: pointer;
}

.radio-group input[type="radio"] {
  appearance: none;
  width: 18px;
  height: 18px;
  border: 2px solid #ddd;
  border-radius: 50%;
  margin-right: 8px;
  transition: all 0.3s ease;
  position: relative;
}

.radio-group input[type="radio"]:checked {
  border-color: #4CAF50;
  background: #4CAF50;
}

.radio-group input[type="radio"]:checked::after {
  content: '';
  position: absolute;
  top: 3px;
  left: 3px;
  width: 8px;
  height: 8px;
  background: white;
  border-radius: 50%;
}

/* 复选框样式 */
.checkbox-group label {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #f8f9fc;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.checkbox-group input[type="checkbox"] {
  appearance: none;
  width: 18px;
  height: 18px;
  border: 2px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
  transition: all 0.3s ease;
  position: relative;
}

.checkbox-group input[type="checkbox"]:checked {
  background: #4CAF50;
  border-color: #4CAF50;
}

.checkbox-group input[type="checkbox"]:checked::after {
  content: '✓';
  position: absolute;
  top: -1px;
  left: 3px;
  color: white;
  font-size: 14px;
}

/* 底部按钮布局 */
.step-content>button {
  margin: 20px 10px 0;
  padding: 10px 24px;
  transition: all 0.3s ease;
}

.step-content>button:last-child {
  background: #4CAF50;
}

.step-content>button:last-child:hover {
  background: #45a049;
}

.step-content>div:last-child {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background: white;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

/* 输入框聚焦效果 */
input:focus,
textarea:focus {
  border-color: #4CAF50 !important;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
  outline: none;
}

/* 新增样式 */
.format-settings-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 25px;
}

.format-setting {
  display: flex;
  align-items: center;
  background: #f8f9fc;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
  margin-bottom: 15px;
  /* 增加行间距 */
}

.format-setting:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(106, 90, 205, 0.1);
}

.format-setting label {
  flex: 0 0 90px;
  font-weight: 500;
  color: #555;
}

.custom-select {
  position: relative;
  flex: 1;
}

.custom-select select {
  width: 100%;
  padding: 10px 35px 10px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  appearance: none;
  background: white;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.select-arrow {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6a5acd;
  font-size: 12px;
  pointer-events: none;
}

.custom-select select:focus {
  border-color: #6a5acd;
  outline: none;
}

.button-group {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.generate-btn {
  background: #4CAF50;
  padding: 12px 30px;
  font-weight: 500;
}

.generate-btn:hover {
  background: #45a049;
  transform: translateY(-1px);
}

/* 新增加载动画样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #6a5acd;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>